//
//  WCAFailListViewController.m
//  WeChatBuniess
//
//  Created by Guo Rui on 2017/12/26.
//  Copyright © 2017年 GR Harry. All rights reserved.
//

#import "WCAFailListViewController.h"
#import "WCACotact.h"
#import "YYModel.h"
#import "WCAFailListCell.h"
#import "WCASessionManager.h"
#import "TFToast.h"

//#define kContactCachePath [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"TFWaitingContact.plist"]
#define kContactCachePath [@"/Users/guorui/Desktop/" stringByAppendingPathComponent:@"TFWaitingContact.plist"]

//#define kContactFailDataDictoryPath [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"TFFailData"]
#define kContactFailDataDictoryPath [@"/Users/guorui/Desktop/" stringByAppendingPathComponent:@"TFFailData"]

@interface WCAFailListViewController ()

@property (strong, nonatomic) NSMutableArray <WCACotact *> *failContactArray;

@end

@implementation WCAFailListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"上传失败列表";
    
    self.tableView.tableFooterView = [[UIView alloc] init];
    [self.tableView registerClass:[WCAFailListCell class] forCellReuseIdentifier:@"ID"];
}

- (NSMutableArray *)failContactArray
{
    if (!_failContactArray) {
        NSFileManager *mag = [NSFileManager defaultManager];
        if ([mag fileExistsAtPath:kContactFailDataDictoryPath] == NO) {
            _failContactArray = @[].mutableCopy;
        }
        else {
            NSArray *dictArray = [NSArray arrayWithContentsOfFile:kContactCachePath];
            NSArray *contactArray = [NSArray yy_modelArrayWithClass:[WCACotact class] json:dictArray];
            NSMutableArray *arrayM = [NSMutableArray arrayWithCapacity:0];
            for (WCACotact *c in contactArray) {
                if (c.tf_status == TFMakeBookStautsCompleteFail) {
                    [arrayM addObject:c];
                }
            }
            _failContactArray = arrayM;
        }
    }
    return _failContactArray;
}

#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.failContactArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    WCAFailListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ID" forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    WCACotact *c = [self.failContactArray objectAtIndex:indexPath.row];
    cell.c = c;
    
    __weak WCAFailListViewController *_self = self;
    cell.retryBlock = ^{
        [_self postDataWithContact:c indexPath:indexPath];
    };
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 80.f;
}

#pragma mark - Private
- (void)postDataWithContact:(WCACotact *)c indexPath:(NSIndexPath *)indexPath
{
    NSString *path = c.tf_errorDataPath;
    if (![[NSFileManager defaultManager] fileExistsAtPath:path]) {
        NSLog(@"%@ - %@ 保存的文件不存在", c.contact.m_nsUsrName, c.tf_errorDataPath);
        WCAFailListCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
        [cell retryEnable];
        
        [self removeCacheWithContact:c];
        
        [self.failContactArray removeObjectAtIndex:indexPath.row];
        [self.tableView reloadData];
        return;
    }
    
    
    NSArray *dictArray = [NSArray arrayWithContentsOfFile:path];
    NSDictionary *dict = @{ @"data" : dictArray,
                            @"from" : @3,
                            @"type" : @0,
                            @"wechatId" : @"xytgr12",
                            @"wechatUserName" : @"郭睿",
                            // TODO: 改成这个
//                            @"wechatId" : c.m_nsUsrName,
//                            @"wechatUserName" : c.m_nsNickName,
                            };
    
    __weak WCAFailListViewController * weakself = self;
    WCAJSONRequestSerializer *serializer = [WCAJSONRequestSerializer serializer];
    [WCASessionManager setRequestSerialization:serializer];
    [WCASessionManager POST:@"tf_wx/mtime/addPartTime" parameters:dict success:^(NSURLSessionDataTask *task, id responseObject) {
        NSString *code = responseObject[@"code"];
        NSString *message = nil;
        NSString *messageForUser = nil;
        BOOL success = NO;
        if ([code isEqualToString:@"000"]) {
            message = @"发送成功";
            messageForUser = @"发送成功";
            success = YES;
        }
        else if ([code isEqualToString:@"TM001001"]) {
            message = @"请求参数不正确";
            messageForUser = @"发送失败，请重试";
        }
        else if ([code isEqualToString:@"TM001002"]) {
            message = @"数据异常";
            messageForUser = @"发送失败，请重试";
        }
        else if ([code isEqualToString:@"TM001003"]) {
            message = @"时光ID不存在";
            messageForUser = @"发送失败，请重试";
        }
        else if ([code isEqualToString:@"TM001004"]) {
            message = @"用户没有发起微信数据导入";
            messageForUser = @"发送失败，请重试";
        }
        
        if (message) {
            dispatch_async(dispatch_get_main_queue(), ^{
                if (success) {
                    [weakself postSuccessHandle:indexPath];
                }
                else {
                    [weakself postFaileHandle:indexPath];
                }
                [TFToast toast:message];
            });
        }
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            NSString *messageForUser = @"您的网络不给力，请重试";
            [TFToast toast:messageForUser];
            [weakself postFaileHandle:indexPath];
        });
    }];
}

- (void)removeCacheWithContact:(WCACotact *)c
{
    NSString *path = c.tf_errorDataPath;
    
    NSMutableArray <NSDictionary *> *contactArray = [NSMutableArray arrayWithContentsOfFile:kContactCachePath];
    NSDictionary *destC = nil;
    for (NSDictionary *cDict in contactArray) {
        if ([cDict[@"contact"][@"m_nsUsrName"] isEqualToString:c.contact.m_nsUsrName]) {
            destC = cDict;
        }
    }
    
    if (destC) {
        [contactArray removeObject:destC];
        [contactArray writeToFile:kContactCachePath atomically:YES];
    }
    
    NSError *error = nil;
    [[NSFileManager defaultManager] removeItemAtPath:path error:&error];
    if (error) {
        NSLog(@"删除文件有错误 %@", error);
    }
}

- (void)postSuccessHandle:(NSIndexPath *)indexPath
{
    // 1. 请求完成接口
    WCACotact *c = [self.failContactArray objectAtIndex:indexPath.row];
    [self uploadCompletedRequest:c.contact];
    
    // 2. 修改按钮状态
    WCAFailListCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
    [cell retryEnable];
    
    // 3. 删除缓存文件
    [self removeCacheWithContact:c];
    
    // 4. 刷新UI
    [self.failContactArray removeObjectAtIndex:indexPath.row];
    [self.tableView reloadData];
}

- (void)postFaileHandle:(NSIndexPath *)indexPath
{
    WCAFailListCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
    [cell retryEnable];
}

- (void)uploadCompletedRequest:(CContact *)c {
    WCAHTTPRequestSerializer *serializer = [WCAHTTPRequestSerializer serializer];
    [WCASessionManager setRequestSerialization:serializer];
    [WCASessionManager POST:@"tf_wx/mtime/wxSendDoneNotify"
                 parameters:@{
                                @"wechatId" : @"xytgr12",
                                @"wechatUserName": @"郭睿"
                                // TODO: 改成这个
//                              @"wechatId" : c.m_nsUsrName,
//                              @"wechatUserName" : c.m_nsNickName
                              }
                    success:^(NSURLSessionDataTask *task, id responseObject) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if ([[responseObject objectForKey:@"code"] isEqualToString:@"000"]) {
                [TFToast toast:@"上传完成通知~"];
            }
            else {
                [TFToast toast:[responseObject objectForKey:@"code"]];
            }
        });
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [TFToast toast:error.localizedDescription];
        });
    }];
}

@end
